<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BDbAdapter
 *
 * @author jianfeng
 */
class BDbAdapter {

    private $app = null;

    public function __construct($app = null) {
        if ($app != null)
            $this->app = $app;
    }

    public function getDbConnection() {
        
        //get connection from config file
        $sApp = $this->app;
        $config = $sApp->getConfigManager();
        $conns = $config->getConfig('db.connection');
        
        if ($this->app->isPreload()) {
            $hostApp = $this->app->getHostApp();
            if ($hostApp instanceof BApp) {
                $preLoadConfig = $hostApp->getConfigManager()->getConfig('preLoad.app.' . get_class($this->app));
                if (isset($preLoadConfig['connection'])) {
                    $connection = $preLoadConfig['connection'];
                    if ($connection != NULL){
                        $conns = $connection;
                    }
                }
            }
        }        

        if ($conns != NULL) {
            $defaultdb = $conns['default'];

            $dbconn = $conns[$defaultdb];

            $connString = isset($dbconn['connectionString']) ? $dbconn['connectionString'] : NULL;
            $userName = isset($dbconn['username']) ? $dbconn['username'] : NULL;
            $password = isset($dbconn['password']) ? $dbconn['password'] : NULL;
            $tblPrefix = isset($dbconn['tablePrefix']) ? $dbconn['tablePrefix'] : NULL;
            $emulatePrepare = isset($dbconn['emulatePrepare']) ? $dbconn['emulatePrepare'] : NULL;
            $charset = isset($dbconn['charset']) ? $dbconn['charset'] : NULL;           

            if ($connString != NULL && $userName != NULL && $password != NULL)
                $conn = new CDbConnection($connString, $userName, $password);

            if ($conn instanceof CDbConnection) {
                if ($emulatePrepare != NULL)
                    $conn->emulatePrepare = $emulatePrepare;
                if ($charset != NULL)
                    $conn->charset = $charset;
                if ($tblPrefix != NULL)
                    $conn->tablePrefix = $tblPrefix;
                //$conn->active = TRUE;
                return $conn;
            }
        }
        return NULL;
    }   

}

?>
